package com.shengqiang.zhenhuiTransfer.utils;

import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.shengqiang.zhenhuiTransfer.config.SysConfigs;
import com.shengqiang.zhenhuiTransfer.entity.Result;
import com.shengqiang.zhenhuiTransfer.entity.WeiXinAccountResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2018/5/20.
 */
@Component
public class WxUtils {

    private static final Logger logger = LoggerFactory.getLogger(WxUtils.class);

    private Gson gson=new Gson();

    public WeiXinAccountResult chekWx(String jsCode) {
        try{
            String appId= SysConfigs.configs.get("mp.appId").getConfigValue();
            if(Strings.isNullOrEmpty(appId)){
                logger.error("appId is null");
                return null;
            }
            String secret=SysConfigs.configs.get("mp.secret").getConfigValue();
            if(Strings.isNullOrEmpty(secret)){
                logger.error("secret is null");
                return null;
            }
            String grant_type=SysConfigs.configs.get("mp.grant_type").getConfigValue();
            String api=SysConfigs.configs.get("mp.loginApi").getConfigValue();
            StringBuilder url=new StringBuilder();
            url.append(api).append("?").append("appid=").append(appId)
                    .append("&secret=").append(secret)
                    .append("&js_code=").append(jsCode)
                    .append("&grant_type=").append(grant_type);
            String result= HttpClientUtil.httpGet(url.toString());
            if(Strings.isNullOrEmpty(result)){
                logger.error("get weixin openid error");
                return null;
            }
            WeiXinAccountResult weixinResult=gson.fromJson(result,WeiXinAccountResult.class);
            return weixinResult;
        }catch (Exception ex){
            logger.error("验证微信信息出现异常:{}",ex.getMessage(),ex);
            return null;
        }
    }
}
